package org.jeecg.modules.analysis.graph.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.analysis.graph.entity.GraphHistory;
import org.jeecg.modules.analysis.graph.mapper.GraphHistoryMapper;
import org.jeecg.modules.analysis.graph.service.IGraphHistoryService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description: 图谱历史记录 Service 实现
 * @Author: dingmengdi
 * @Date: 2025-10-13
 * @Version: V1.0
 */
@Service
@Slf4j
public class GraphHistoryServiceImpl extends ServiceImpl<GraphHistoryMapper, GraphHistory> implements IGraphHistoryService {

    @Override
    public void saveOrUpdateHistory(String patentId, String patentName, String relationType) {
        // 从 Shiro 上下文获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getUsername();
        
        log.info("保存图谱访问记录: userId={}, patentId={}, relationType={}", userId, patentId, relationType);

        // 查询是否存在该用户对该专利的访问记录（使用 create_by 作为用户标识）
        QueryWrapper<GraphHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by", userId);
        queryWrapper.eq("patent_id", patentId);
        
        GraphHistory existingHistory = this.getOne(queryWrapper);
        
        if (existingHistory != null) {
            // 存在则更新：访问次数+1，更新关联类型
            // updateTime 和 updateBy 由 MyBatis-Plus 自动填充（作为最后访问时间）
            existingHistory.setVisitCount(existingHistory.getVisitCount() + 1);
            existingHistory.setRelationType(relationType);
            existingHistory.setPatentName(patentName);
            this.updateById(existingHistory);
            log.info("更新访问记录成功，访问次数: {}", existingHistory.getVisitCount());
        } else {
            // 不存在则新增
            // createTime, createBy, updateTime, updateBy 由 MyBatis-Plus 自动填充
            GraphHistory newHistory = new GraphHistory();
            newHistory.setPatentId(patentId);
            newHistory.setPatentName(patentName);
            newHistory.setRelationType(relationType);
            newHistory.setVisitCount(1);
            this.save(newHistory);
            log.info("新增访问记录成功");
        }
    }

    @Override
    public GraphHistory getLastVisit() {
        // 从 Shiro 上下文获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getUsername();
        
        log.info("获取用户最后访问记录: userId={}", userId);

        // 查询该用户最近访问的记录（使用 create_by 作为用户标识，按 update_time 排序）
        QueryWrapper<GraphHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by", userId);
        queryWrapper.orderByDesc("update_time");
        queryWrapper.last("LIMIT 1");
        
        GraphHistory lastVisit = this.getOne(queryWrapper);
        
        if (lastVisit != null) {
            log.info("找到最后访问记录: patentId={}, patentName={}", lastVisit.getPatentId(), lastVisit.getPatentName());
        } else {
            log.info("未找到访问记录");
        }
        
        return lastVisit;
    }
}

